<template>
  <div class="edit">
    <img src="../assets/logo.png" alt="" class="logo">
    <el-form ref="ruleFormRef" :model="editForm" :rules="editRules" label-position="left" label-width="auto">
      <el-form-item label="邮箱" prop="user_email">
        <el-input  placeholder="请输入邮箱地址" v-model="editForm.user_email"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="user_password">
        <el-input  placeholder="请输入新密码" v-model="editForm.user_password" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="user_confirm">
        <el-input  placeholder="请再次输入新密码" v-model="editForm.user_confirm" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="sendEmail(ruleFormRef)">获取验证码</el-button>
        <el-input  class='code' placeholder="请输入验证码" v-model="editForm.user_myCode"></el-input>
      </el-form-item>
      <el-form-item>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          <el-button @click="edit(ruleFormRef)" type="primary">修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { ElMessage, FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'
import { defineComponent, reactive, ref } from 'vue'
import axios from 'axios'

export default defineComponent({
  name: 'EditView',
  setup () {
    let code = ''
    let email = ''
    const userEmail = sessionStorage.getItem('userE')
    const router = useRouter()
    const ruleFormRef = ref<FormInstance>()
    const editForm = reactive({
      user_email: '',
      user_password: '',
      user_confirm: '',
      user_myCode: ''
    })
    const validatePassword = (rule: any, value: any, callback: any) => {
      if (value !== editForm.user_password) {
        callback(new Error('两次输入的密码不一致'))
      } else { callback() }
    }
    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.resetFields()
    }

    const sendEmail = async (formEl: FormInstance|undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          axios.post('http://localhost:8081/sendEmail', editForm).then(res => {
            if (res.data != null) {
              code = res.data + ''
              email = editForm.user_email
              ElMessage.success('验证码发送成功，请注意查收')
            } else {
              ElMessage.error('服务器繁忙')
            }
          })
        } else {
          console.log('error send', fields)
        }
      })
    }

    const edit = async (formEl: FormInstance|undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          if (editForm.user_myCode === '') {
            ElMessage.error('请输入验证码')
          } else if (editForm.user_myCode !== code) {
            ElMessage.error('验证码错误')
          } else if (editForm.user_email !== email) {
            editForm.user_myCode = ''
            ElMessage.error('您已修改邮箱地址，请重新获取验证码')
          } else {
            axios.post('http://localhost:8081/edit', editForm).then(res => {
              if (res.data === 'ok') {
                ElMessage.success('修改成功！请重新登陆')
                router.push('/login')
              } else if (res.data === 'error') {
                ElMessage.error('服务器繁忙')
              }
            }).catch(error => {
              console.log(error)
            })
          }
        } else {
          console.log('error submit', fields)
        }
      })
    }
    const editRules = reactive({
      user_email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { whitespace: true, type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      user_password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { whitespace: true, message: '请输入正确格式', trigger: 'blur' },
        { min: 6, max: 15, message: '密码位数只能在6~15之间', trigger: 'blur' }
      ],
      user_confirm: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
        { whitespace: true, message: '请输入正确格式', trigger: 'blur' },
        { min: 6, max: 15, message: '密码位数只能在6~15之间', trigger: 'blur' },
        { validator: validatePassword, trigger: 'blur' }
      ]
    })
    return {
      editRules,
      editForm,
      resetForm,
      ruleFormRef,
      edit,
      sendEmail,
      code,
      email,
      userEmail
    }
  }
})
</script>

<style scoped>
.edit{
width: 450px;
margin: 180px auto;
border: 1px solid #efefef;
padding: 20px;
border-radius: 10px;
margin-top: 100px;
}
.logo{
  margin-bottom: 20px;
}
h4{
  text-align: center;
}
.code{
  width: 75%;
  margin-left: 10px;
}
</style>
<style>
.el-form-item_content{
  text-align: center;
}
.el-button+.el-button {
    margin-left: 330px;
}
</style>
